package ks.app.smartDic;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.AttributeSet;

public class AutoCompleteTextForNaverDic extends AutoCompleteTextView {

	private List<String> resultForAdaptor;

	private String previous = "";
	private String seperator = ";";
	private String targetURL;
	private final String[] COUNTRIES;
	ArrayAdapter<String> defaultAdapter;
	ArrayAdapter<String> taskAdapter;
	private Context context;
	searchWordFromNaver sn;

	public AutoCompleteTextForNaverDic(final Context context,
			final AttributeSet attrs, final int defStyle) {

		super(context, attrs, defStyle);
		this.context = context;
		
		COUNTRIES = new String[] { "Belgium" };
		
		defaultAdapter = new ArrayAdapter<String>(
				this.context, android.R.layout.simple_dropdown_item_1line,
				COUNTRIES);
		setAdapter(defaultAdapter);
		
		this.setThreshold(2);
	}

	public AutoCompleteTextForNaverDic(final Context context,
			final AttributeSet attrs) {
		super(context, attrs);

		ksLog.d("start");
		this.context = context;

		COUNTRIES = new String[] { "Belgium" };
		defaultAdapter = new ArrayAdapter<String>(
				this.context, android.R.layout.simple_dropdown_item_1line,
				COUNTRIES);
		setAdapter(defaultAdapter);

		this.setThreshold(2);
	}
	
	public void setURL(String pURL)
	{
		this.targetURL = pURL;
	}


	@Override
	protected void performFiltering(final CharSequence text, final int keyCode) {

		ksLog.d("wow", text.toString());
		
		sn = new searchWordFromNaver(this.context, this);
		sn.execute(text.toString(), targetURL);

		String filterText = text.toString().trim();
		previous = filterText.substring(0,
				filterText.lastIndexOf(getSeperator()) + 1);
		filterText = filterText.substring(filterText
				.lastIndexOf(getSeperator()) + 1);
		if (!TextUtils.isEmpty(filterText)) {
			super.performFiltering(filterText, keyCode);
		}
	}

	/**
	 * After a selection, capture the new value and append to the existing text
	 */
	@Override
	protected void replaceText(final CharSequence text) {
		ksLog.d("previous",previous);
		super.replaceText(previous + text);
	}

	public String getSeperator() {
		return seperator;
	}

	public void setSeperator(final String seperator) {
		this.seperator = seperator;
	}

	private class searchWordFromNaver extends AsyncTask<String, String, String> {

		AutoCompleteTextForNaverDic mAutoCompleteTextForNaverDic;
		private List<String> wordList;

		searchWordFromNaver(Context pContext,
				AutoCompleteTextForNaverDic pAutoCompleteTextForNaverDic) {
			
			wordList = new ArrayList<String>();
			resultForAdaptor = new ArrayList<String>();
			taskAdapter = new ArrayAdapter<String>(pContext, android.R.layout.simple_dropdown_item_1line,resultForAdaptor);
			this.mAutoCompleteTextForNaverDic = pAutoCompleteTextForNaverDic;
		}

		@Override
		protected String doInBackground(String... param) {

			ksLog.d("start");
			ksLog.d("param", param[0]);

			httpClient hc = new httpClient();
			
			try {
				 
				String targetUrl = param[1]
				    					 + URLEncoder.encode(param[0], "UTF-8");
				
				hc.post(targetUrl);
				
				JSONObject jsonObj = new JSONObject(hc.generateString());

				JSONArray items = jsonObj.getJSONArray("items");

				ksLog.d("length", items.length());

				for (int i = 0; i < items.length(); i++) {

					for (int j = i; j < ((JSONArray) items.get(i)).length(); j++) {

						wordList.add(((JSONArray) ((JSONArray) items
								.get(i)).get(j)).getString(0)
								.replace("[\"", "").replace("\"]", ""));

					}
				}

			} catch (Exception e) {
				ksLog.d("e", e.getMessage());
			}

			return null;
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(String... values) {

		}

		protected void onPostExecute(String result) {

			try {
				
				for(int i = 0; i < wordList.size() -1 ; i++ )
					resultForAdaptor.add(wordList.get(i).toString());
				
				this.mAutoCompleteTextForNaverDic.setAdapter(taskAdapter);
				this.mAutoCompleteTextForNaverDic.showDropDown();
			} catch (Exception e) {
				ksLog.d("e", e.getMessage());
			}

		}

	}

}